package com.luli.Utils;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 陆离
 * 2022/10/18 15:40:56
 */
@Slf4j
public class JwtUtils {


    private static final String jwtToken = "123456Mszlu!@#$";

    /**
     * 生成token
     *
     * @param userId
     * @return
     */
    public static String createJwtToken(Long userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtToken) //签发算法，密钥为jwtToken
                .setClaims(claims)          //body数据，要唯一，自行设置
                .setIssuedAt(new Date())     //设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)); //一天的有效期
        String token = jwtBuilder.compact();
        return token;
    }

    public static Map<String, Object> checkToken(String token) {
        try {
            Jwt parse = Jwts.parser().setSigningKey(jwtToken).parse(token);
            return (Map<String, Object>) parse.getBody();
        } catch (Exception e) {
            log.error("Token校验失败");
            e.printStackTrace();
        }
        return null;
    }

}
